/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "errorhandling_fuzzer.h"
#include "fuzz_common_base.h"

#include "notification_helper.h"
#include "notification_request.h"
#include "notification_slot.h"
#include "notification_normal_content.h"
#include "notification_bundle_option.h"
#include <fuzzer/FuzzedDataProvider.h>

namespace OHOS {
    namespace {
        constexpr uint8_t TEST_SCENARIOS = 10;
        constexpr int32_t NOTIFICATION_ID_BASE_NULL_TEST = 0;
        constexpr int32_t NOTIFICATION_ID_BASE_MEMORY_TEST = 40000;
        constexpr int32_t NOTIFICATION_ID_BASE_DANGLING_TEST = 50000;
        constexpr int32_t NOTIFICATION_ID_BASE_RECURSIVE_TEST = 60000;
        constexpr int32_t NOTIFICATION_ID_BASE_LEAK_TEST = 70000;
        constexpr int32_t INVALID_SLOT_TYPE_VALUE = 999;
        constexpr int32_t SLOT_RANGE_START = -10;
        constexpr int32_t SLOT_RANGE_END = 20;
        constexpr uint8_t BATCH_CANCEL_INTERVAL = 10;
        constexpr uint16_t HUGE_STRING_SIZE = 5000;
        constexpr uint16_t HUGE_STRING_BASE_SIZE = 10000;
        constexpr uint16_t HUGE_STRING_INCREMENT = 1000;
        constexpr uint8_t EXHAUSTION_LEVEL_COUNT = 5;
        constexpr uint16_t BASE_ITEM_COUNT = 100;
        constexpr uint16_t ITEM_COUNT_MULTIPLIER = 100;
        constexpr uint16_t CLEAR_INTERVAL = 50;
        constexpr uint8_t OPERATION_COUNT_MODULO = 30;
        constexpr uint8_t OPERATION_COUNT_BASE = 20;
        constexpr uint8_t OPERATION_TYPE_COUNT = 10;
        constexpr uint8_t RECURSION_LEVEL_MODULO = 10;
        constexpr uint8_t RECURSION_LEVEL_BASE = 1;
        constexpr uint8_t LEAK_TEST_MODULO = 50;
        constexpr uint8_t LEAK_TEST_BASE = 25;
        constexpr int32_t INVALID_ID_TEST_VALUE = -999999;
        constexpr size_t CORRUPTED_STRING_PREFIX_LENGTH = 1;
        constexpr size_t CORRUPTED_STRING_LARGE_SIZE = 10000;
        constexpr uint8_t CORRUPTED_CHAR_HIGH = 0x80;
        constexpr uint8_t CORRUPTED_CHAR_MAX = 0xFF;
        constexpr size_t RANDOM_STRING_MIN_LENGTH = 0;
        constexpr int32_t BUNDLE_UID_ZERO = 0;
        constexpr int32_t BUNDLE_UID_NEGATIVE = -1;
        constexpr size_t BUNDLE_NAME_LARGE_SIZE = 5000;
        constexpr int32_t BUNDLE_UID_INVALID = -999;
        constexpr int32_t INVALID_NOTIFICATION_ID = -1;
        constexpr int32_t INVALID_SLOT_TYPE_ID = -1;
        
        enum TestScenario {
            SCENARIO_NULL_POINTER = 0,
            SCENARIO_INVALID_IDS = 1,
            SCENARIO_INVALID_SLOT = 2,
            SCENARIO_CORRUPTED_STRING = 3,
            SCENARIO_INVALID_BUNDLE = 4,
            SCENARIO_MEMORY_EXHAUSTION = 5,
            SCENARIO_CONCURRENT_ERROR = 6,
            SCENARIO_DANGLING_POINTER = 7,
            SCENARIO_RECURSIVE_OPS = 8,
            SCENARIO_RESOURCE_LEAK = 9
        };
        
        enum ConcurrentOperation {
            OP_CANCEL_INVALID = 0,
            OP_REMOVE_INVALID_SLOT = 1,
            OP_INVALID_BUNDLE = 2,
            OP_SET_INVALID_BADGE = 3,
            OP_GET_ACTIVE = 4,
            OP_GET_SLOTS = 5,
            OP_CANCEL_GROUP = 6,
            OP_GET_SLOT = 7,
            OP_GET_SLOTS_DUP = 8,
            OP_GET_BADGE = 9
        };
    }
    
    bool TestNullPointerHandling(FuzzedDataProvider* fdp)
    {
        Notification::NotificationRequest request;
        request.SetContent(nullptr);
        request.SetNotificationId(fdp->ConsumeIntegral<int32_t>());
        
        (void)Notification::NotificationHelper::PublishNotification(request);
        
        std::vector<sptr<Notification::NotificationRequest>> notifications;
        Notification::NotificationHelper::GetActiveNotifications(notifications);
        
        return true;
    }
    
    bool TestInvalidNotificationIds(FuzzedDataProvider* fdp)
    {
        std::vector<int32_t> invalidIds = {
            INT32_MIN, INT32_MAX, INVALID_ID_TEST_VALUE, NOTIFICATION_ID_BASE_NULL_TEST,
            fdp->ConsumeIntegral<int32_t>()
        };
        
        for (int32_t id : invalidIds) {
            Notification::NotificationHelper::CancelNotification(id);
            
            Notification::NotificationRequest request;
            std::shared_ptr<Notification::NotificationNormalContent> normalContent =
                std::make_shared<Notification::NotificationNormalContent>();
            normalContent->SetTitle("Invalid ID Test");
            std::shared_ptr<Notification::NotificationContent> content =
                std::make_shared<Notification::NotificationContent>(normalContent);
            request.SetContent(content);
            request.SetNotificationId(id);
            
            Notification::NotificationHelper::PublishNotification(request);
        }
        
        Notification::NotificationHelper::CancelAllNotifications();
        return true;
    }
    
    bool TestInvalidSlotOperations(FuzzedDataProvider* fdp)
    {
        for (int i = SLOT_RANGE_START; i < SLOT_RANGE_END; i++) {
            Notification::NotificationConstant::SlotType slotType =
                Notification::NotificationConstant::SlotType(i);
            
            Notification::NotificationSlot slot;
            slot.SetType(slotType);
            slot.SetDescription("Invalid Slot Test");
            
            Notification::NotificationHelper::AddNotificationSlot(slot);
            Notification::NotificationHelper::RemoveNotificationSlot(slotType);
            
            sptr<Notification::NotificationSlot> retrievedSlot;
            Notification::NotificationHelper::GetNotificationSlot(slotType, retrievedSlot);
        }
        
        return true;
    }
    
    bool TestCorruptedStringData(FuzzedDataProvider* fdp)
    {
        std::vector<std::string> corruptedStrings = {
            std::string(CORRUPTED_STRING_PREFIX_LENGTH, '\0') + "corrupted",
            std::string("\x01\x02\x03\x04\x05"),
            std::string(CORRUPTED_STRING_LARGE_SIZE, '\xFF'),
            std::string("") + char(CORRUPTED_CHAR_HIGH) + char(CORRUPTED_CHAR_MAX),
            fdp->ConsumeRandomLengthString(RANDOM_STRING_MIN_LENGTH)
        };
        
        for (const std::string& corruptedStr : corruptedStrings) {
            Notification::NotificationRequest request;
            std::shared_ptr<Notification::NotificationNormalContent> normalContent =
                std::make_shared<Notification::NotificationNormalContent>();
            normalContent->SetTitle(corruptedStr);
            normalContent->SetText(corruptedStr);
            normalContent->SetAdditionalText(corruptedStr);
            
            std::shared_ptr<Notification::NotificationContent> content =
                std::make_shared<Notification::NotificationContent>(normalContent);
            request.SetContent(content);
            request.SetNotificationId(fdp->ConsumeIntegral<int32_t>());
            request.SetLabel(corruptedStr);
            request.SetGroupName(corruptedStr);
            
            Notification::NotificationHelper::PublishNotification(request);
        }
        
        Notification::NotificationHelper::CancelAllNotifications();
        return true;
    }
    
    bool TestInvalidBundleOperations(FuzzedDataProvider* fdp)
    {
        std::vector<std::pair<std::string, int32_t>> invalidBundles = {
            {"", BUNDLE_UID_ZERO},
            {"", BUNDLE_UID_NEGATIVE},
            {"", INT32_MAX},
            {std::string(BUNDLE_NAME_LARGE_SIZE, 'X'), BUNDLE_UID_ZERO},
            {"\0invalid\0bundle\0", BUNDLE_UID_INVALID},
            {"valid.bundle", INT32_MIN}
        };
        
        for (const auto& bundle : invalidBundles) {
            Notification::NotificationBundleOption bundleOption;
            bundleOption.SetBundleName(bundle.first);
            bundleOption.SetUid(bundle.second);
            
            std::vector<sptr<Notification::NotificationSlot>> slots;
            Notification::NotificationHelper::GetNotificationSlotsForBundle(bundleOption, slots);
            
            int32_t badgeNumber = fdp->ConsumeIntegral<int32_t>();
            Notification::NotificationHelper::SetBadgeNumberByBundle(bundleOption, badgeNumber);
        }
        
        return true;
    }
    
    bool TestMemoryExhaustionScenarios(FuzzedDataProvider* fdp)
    {
        uint8_t exhaustionLevel = fdp->ConsumeIntegral<uint8_t>() % EXHAUSTION_LEVEL_COUNT;
        uint16_t itemCount = BASE_ITEM_COUNT + exhaustionLevel * ITEM_COUNT_MULTIPLIER;
        
        std::vector<std::string> hugeStrings;
        for (uint16_t i = 0; i < itemCount; i++) {
            std::string hugeString = std::string(HUGE_STRING_BASE_SIZE + i * HUGE_STRING_INCREMENT, 'M');
            hugeStrings.push_back(hugeString);
            
            Notification::NotificationRequest request;
            std::shared_ptr<Notification::NotificationNormalContent> normalContent =
                std::make_shared<Notification::NotificationNormalContent>();
            normalContent->SetTitle(hugeString);
            normalContent->SetText(hugeString);
            
            std::shared_ptr<Notification::NotificationContent> content =
                std::make_shared<Notification::NotificationContent>(normalContent);
            request.SetContent(content);
            request.SetNotificationId(i + NOTIFICATION_ID_BASE_MEMORY_TEST);
            
            (void)Notification::NotificationHelper::PublishNotification(request);
            
            if (i % CLEAR_INTERVAL == 0) {
                Notification::NotificationHelper::CancelAllNotifications();
                hugeStrings.clear();
            }
        }
        
        Notification::NotificationHelper::CancelAllNotifications();
        return true;
    }
    
    void ExecuteConcurrentOperation(uint8_t operationType)
    {
        switch (operationType) {
            case OP_CANCEL_INVALID:
                Notification::NotificationHelper::CancelNotification(INVALID_NOTIFICATION_ID);
                break;
            case OP_REMOVE_INVALID_SLOT:
                Notification::NotificationHelper::RemoveNotificationSlot(
                    Notification::NotificationConstant::SlotType(INVALID_SLOT_TYPE_VALUE));
                break;
            case OP_INVALID_BUNDLE: {
                Notification::NotificationBundleOption invalidBundle;
                invalidBundle.SetBundleName("");
                invalidBundle.SetUid(BUNDLE_UID_NEGATIVE);
                std::vector<sptr<Notification::NotificationSlot>> slots;
                Notification::NotificationHelper::GetNotificationSlotsForBundle(invalidBundle, slots);
                break;
            }
            case OP_SET_INVALID_BADGE:
                Notification::NotificationHelper::SetBadgeNumber(INT32_MIN);
                break;
            case OP_GET_ACTIVE: {
                std::vector<sptr<Notification::NotificationRequest>> notifications;
                Notification::NotificationHelper::GetActiveNotifications(notifications);
                break;
            }
            case OP_GET_SLOTS:
            case OP_GET_SLOTS_DUP: {
                std::vector<sptr<Notification::NotificationSlot>> slots;
                Notification::NotificationHelper::GetNotificationSlots(slots);
                break;
            }
            case OP_CANCEL_GROUP:
                Notification::NotificationHelper::CancelGroup("");
                break;
            case OP_GET_SLOT: {
                sptr<Notification::NotificationSlot> slot;
                Notification::NotificationHelper::GetNotificationSlot(
                    Notification::NotificationConstant::SlotType(INVALID_SLOT_TYPE_ID), slot);
                break;
            }
            case OP_GET_BADGE: {
                int32_t badge;
                Notification::NotificationHelper::GetBadgeNumber(badge);
                break;
            }
            default:
                break;
        }
    }
    
    bool TestConcurrentErrorScenarios(FuzzedDataProvider* fdp)
    {
        uint8_t operationCount = fdp->ConsumeIntegral<uint8_t>() % OPERATION_COUNT_MODULO + OPERATION_COUNT_BASE;
        
        for (uint8_t i = 0; i < operationCount; i++) {
            uint8_t operationType = fdp->ConsumeIntegral<uint8_t>() % OPERATION_TYPE_COUNT;
            ExecuteConcurrentOperation(operationType);
        }
        
        return true;
    }
    
    bool TestDanglingPointerScenarios(FuzzedDataProvider* fdp)
    {
        {
            auto normalContent = std::make_shared<Notification::NotificationNormalContent>();
            normalContent->SetTitle("Dangling Test");
            auto content = std::make_shared<Notification::NotificationContent>(normalContent);
            
            Notification::NotificationRequest request;
            request.SetContent(content);
            request.SetNotificationId(NOTIFICATION_ID_BASE_DANGLING_TEST);
            
            Notification::NotificationHelper::PublishNotification(request);
        }
        
        std::vector<sptr<Notification::NotificationRequest>> notifications;
        Notification::NotificationHelper::GetActiveNotifications(notifications);
        
        Notification::NotificationHelper::CancelNotification(NOTIFICATION_ID_BASE_DANGLING_TEST);
        
        return true;
    }
    
    bool TestRecursiveOperations(FuzzedDataProvider* fdp)
    {
        uint8_t recursionLevel = fdp->ConsumeIntegral<uint8_t>() % RECURSION_LEVEL_MODULO + RECURSION_LEVEL_BASE;
        
        for (uint8_t level = 0; level < recursionLevel; level++) {
            Notification::NotificationRequest request;
            std::shared_ptr<Notification::NotificationNormalContent> normalContent =
                std::make_shared<Notification::NotificationNormalContent>();
            normalContent->SetTitle("Recursive Level " + std::to_string(level));
            
            std::shared_ptr<Notification::NotificationContent> content =
                std::make_shared<Notification::NotificationContent>(normalContent);
            request.SetContent(content);
            request.SetNotificationId(NOTIFICATION_ID_BASE_RECURSIVE_TEST + level);
            
            ErrCode publishResult = Notification::NotificationHelper::PublishNotification(request);
            if (publishResult != ERR_OK) {
                continue;
            }
            
            std::vector<sptr<Notification::NotificationRequest>> notifications;
            Notification::NotificationHelper::GetActiveNotifications(notifications);
            
            for (auto& notification : notifications) {
                int32_t expectedId = NOTIFICATION_ID_BASE_RECURSIVE_TEST + level;
                if (notification && notification->GetNotificationId() == expectedId) {
                    Notification::NotificationHelper::CancelNotification(expectedId);
                    break;
                }
            }
        }
        
        return true;
    }
    
    bool TestResourceLeakScenarios(FuzzedDataProvider* fdp)
    {
        uint8_t leakTestCount = fdp->ConsumeIntegral<uint8_t>() % LEAK_TEST_MODULO + LEAK_TEST_BASE;
        
        for (uint8_t i = 0; i < leakTestCount; i++) {
            std::shared_ptr<Notification::NotificationNormalContent> normalContent =
                std::make_shared<Notification::NotificationNormalContent>();
            normalContent->SetTitle("Leak Test " + std::to_string(i));
            normalContent->SetText(std::string(HUGE_STRING_SIZE, 'L'));
            
            std::shared_ptr<Notification::NotificationContent> content =
                std::make_shared<Notification::NotificationContent>(normalContent);
            
            Notification::NotificationRequest request;
            request.SetContent(content);
            request.SetNotificationId(NOTIFICATION_ID_BASE_LEAK_TEST + i);
            
            Notification::NotificationHelper::PublishNotification(request);
            
            if (i % BATCH_CANCEL_INTERVAL == 0) {
                for (uint8_t j = 0; j < BATCH_CANCEL_INTERVAL; j++) {
                    Notification::NotificationHelper::CancelNotification(NOTIFICATION_ID_BASE_LEAK_TEST + i - j);
                }
            }
        }
        
        Notification::NotificationHelper::CancelAllNotifications();
        return true;
    }
    
    bool DoSomethingInterestingWithMyAPI(FuzzedDataProvider* fdp)
    {
        uint8_t scenario = fdp->ConsumeIntegral<uint8_t>() % TEST_SCENARIOS;
        
        switch (scenario) {
            case SCENARIO_NULL_POINTER:
                return TestNullPointerHandling(fdp);
            case SCENARIO_INVALID_IDS:
                return TestInvalidNotificationIds(fdp);
            case SCENARIO_INVALID_SLOT:
                return TestInvalidSlotOperations(fdp);
            case SCENARIO_CORRUPTED_STRING:
                return TestCorruptedStringData(fdp);
            case SCENARIO_INVALID_BUNDLE:
                return TestInvalidBundleOperations(fdp);
            case SCENARIO_MEMORY_EXHAUSTION:
                return TestMemoryExhaustionScenarios(fdp);
            case SCENARIO_CONCURRENT_ERROR:
                return TestConcurrentErrorScenarios(fdp);
            case SCENARIO_DANGLING_POINTER:
                return TestDanglingPointerScenarios(fdp);
            case SCENARIO_RECURSIVE_OPS:
                return TestRecursiveOperations(fdp);
            case SCENARIO_RESOURCE_LEAK:
                return TestResourceLeakScenarios(fdp);
            default:
                return TestNullPointerHandling(fdp);
        }
    }
}

/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
    /* Run your code on data */
    std::vector<std::string> permissions;
    NativeTokenGet(permissions);
    FuzzedDataProvider fdp(data, size);
    OHOS::DoSomethingInterestingWithMyAPI(&fdp);
    return 0;
}
